package com.hougong.im.utils;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;

import java.util.Date;

public class JwtUtils {
    private static final String SECRET_KEY = "666";

    private JwtUtils(){}

    /**
     * 生成jwt token
     *
     * @return
     */
    public static String generateToken(Long uId, String phone) {
        // 生成token
        String jwtToken = Jwts.builder()
                // 头部
                .setHeaderParam("typ", "JWT")
                // jwt 标注中的申明
                .setIssuedAt(new Date()) // 签发时间
                .setExpiration(new Date(new Date().getTime() + (1000L * 60 * 60 * 24 * 30)))// 过期时间
                .setIssuer("hougong.im")// jwt的签发者

                // 公共申明和私有申明
                .claim("uid", uId)
                .claim("phone", phone)

                // 签证
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY.getBytes())

                .compact();

        System.out.println("生成的 jwt token 如下:" + jwtToken);
        return jwtToken;
    }

    /**
     * 解析jwt成对象
     *
     * @param token
     * @return
     */
    public static Jws<Claims> parse(String token) {
        Jws<Claims> claimsJws = Jwts.parser()
                // 验证签发者字段iss 必须是 huan
                .require("iss", "hougong.im")
                // 设置私钥
                .setSigningKey(SECRET_KEY.getBytes())
                // 解析jwt字符串
                .parseClaimsJws(token);

        // 获取头部信息
        JwsHeader header = claimsJws.getHeader();
        // 获取载荷信息
        Claims payload = claimsJws.getBody();
        Long uid = payload.get("uid", Long.class);
        String phone = payload.get("phone", String.class);
        System.out.println("uid :" + uid + " phone :" + phone);
        System.out.println("解析过来的jwt的header如下:" + header.toString());
        System.out.println("解析过来的jwt的payload如下:" + payload.toString());
        return claimsJws;
    }

    public static Long getTokenUid(String token){
        Jws<Claims> parse = parse(token);
        final Long uid = parse.getBody().get("uid", Long.class);
        return uid;
    }

    public static String getTokenPhone(String token){
        Jws<Claims> parse = parse(token);
        String phone = parse.getBody().get("phone", String.class);
        return phone;
    }


    public static int parse2StrTo10(String str2){
        int sum=0;
        for(int i=str2.length()-1,j=0;i>=0;i--,j++){
            if(str2.charAt(i)=='1'){
                 sum+=(1<<j);
            }
        }
        return sum;
    }
    public static void main(String[] args) {
        System.out.println(parse2StrTo10("1111"));
        JwtUtils.getTokenUid(JwtUtils.generateToken(1L, "1234858"));
        Date date=new Date();
        System.out.println(JSON.toJSONString(date));
    }
}
